﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;

using Ivy.Common.Framework.GeneralUtility;
using Ivy.SiteAdmin.Entity;
using Ivy.SiteAdmin.BusinessLogic;
using Ivy.SiteAdmin.DataAccess;
using Ivy.SiteAdmin.IBusinessLogic;

namespace DasIdeen.Pages
{
    public partial class ErrorSummaryReport : System.Web.UI.Page
    {
        #region  Variable & constant
        //All constants and local variable should be declared here
        #endregion  Variable & constant

        #region Constructor & Destructor
        //Generally not needed in UI layer
        #endregion Constructor & Destructor

        #region Properties
        //UI layer may have public custom properties. these are very handy for User Controls
        #endregion Properties

        #region Public Methods
        //UI layer may have public custom properties. these are very handy for User Controls
        #endregion Public Methods

        #region Events
        protected void Page_Load(object sender, EventArgs e)
        {
            try //All events in pages or user control should have try{} catch {} block.
            {
                //First check if the current logged in user is having proper role/authorization to access this page or not.
                if (IsUserAutherization())
                {
                    LoadSys_ErrorLogList();
                    //TODO - Your code to display the initial layout/data etc.
                }
                else
                {
                    //TODO - Your code to redirect page to "NOT AUTHORIZED" page or any other page as required by the business logic.
                }
            }
            catch (Exception ex)
            {
                ExceptionUtility.ExceptionHandler(ex, Server.MapPath("~/"));
            }
        }

        protected void btnDownload_Click(object sender, EventArgs e)
        {
            List<Sys_ErrorLog> lSys_ErrorLogList = new List<Sys_ErrorLog>();
            SiteAdminContentManagementBus lSiteAdminContentManagementBus = new SiteAdminContentManagementBus();
            lSys_ErrorLogList = lSiteAdminContentManagementBus.GetAllSys_ErrorLogDetails();

            if (lSys_ErrorLogList.Count > 0)
            {
                string header = @"""ErrorLogPrimaryID"",""ApplicationName"",""MethodName"",""ErrorMessage"",""StackTrace"",""Sys_DateOfCreation""";

                StringBuilder sb = new StringBuilder();
                sb.AppendLine(header);
                foreach (Sys_ErrorLog lSys_ErrorLog in lSys_ErrorLogList)
                {
                    sb.AppendLine(string.Join(",",
                        string.Format(@"""{0}""", lSys_ErrorLog.ErrorLogPrimaryID),
                        string.Format(@"""{0}""", lSys_ErrorLog.ApplicationName),
                        string.Format(@"""{0}""", lSys_ErrorLog.MethodName),
                        string.Format(@"""{0}""", lSys_ErrorLog.ErrorMessage),
                        string.Format(@"""{0}""", lSys_ErrorLog.StackTrace),
                        string.Format(@"""{0}""", lSys_ErrorLog.Sys_DateOfCreation)));
                }
                HttpContext context = HttpContext.Current;
                context.Response.Write(sb.ToString());
                context.Response.ContentType = "text/csv";
                context.Response.AddHeader("Content-Disposition", "attachment; filename=Sys_ErrorLogDetails.csv");
                context.Response.End();
            }
        }


        protected void lblApplicationName_Click(object sender, EventArgs e)
        {
            int key = Convert.ToInt32(Request.QueryString["id"].ToString());
            SiteAdminContentManagementBus lSiteAdminContentManagementBus = new SiteAdminContentManagementBus();
            Sys_ErrorLog _Sys_ErrorLog = lSiteAdminContentManagementBus.GetSelectedSys_ErrorLogByErrorLogPrimaryID(key);
            TranslateEntityToUIControls(_Sys_ErrorLog);
            this.ModalPopupExtender1.Show();

        }

        //protected void gvdErrorLog_DataBound(object sender, GridViewRowEventArgs e)
        //{
        //    if (e.Row.RowType == DataControlRowType.DataRow)
        //    {
        //        if (e.Row.Cells[4].Text.ToString().Length >5)
        //        {
        //            e.Row.Cells[4].Text = e.Row.Cells[4].Text.ToString().Substring(0, 5) + "...";
        //        }
        //    }

        //}

        //protected void gvdErrorLog_DataBound(object sender, GridViewRowEventArgs e)
        //{

        //    int i = 0;

        //    e.Row.Cells[4].Visible = false;

        //    if (e.Row.RowType == DataControlRowType.EmptyDataRow)
        //    {

        //        foreach (TableCell cell in e.Row.Cells)
        //        {

        //            i++;

        //            string s = cell.Text;

        //            if (cell.Text.Length > 25 && (i == 3))

        //                cell.Text = cell.Text.Substring(0, 25) + "....";

        //            cell.ToolTip = s;

        //        }

        //    }

        //}

        protected void gvdErrorLog_DataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowIndex < 0)
                return;

            int _myColumnIndex = 4;   // Substitute your value here

            for (_myColumnIndex = 0; _myColumnIndex <= 4; _myColumnIndex++)
            {
                string text = e.Row.Cells[_myColumnIndex].Text;

                if (text.Length > 25)
                {
                    e.Row.Cells[_myColumnIndex].Text = text.Substring(0, 25) + "...";
                }
            }

        }

        #endregion Events

        #region Private Methods

        /// <summary>
        /// This method is to check if the current logged in user is having proper role/authorization to access this page or not.
        /// </summary>
        private bool IsUserAutherization()
        {
            bool _IsUserAutherization = false;
            //TODO - Your code to check authorization goes here.

            //for the time being let us allow the user to access this page.
            //but remove the below line once you have a proper logic.
            _IsUserAutherization = true;

            return _IsUserAutherization;
        }

        /// <summary>
        /// This method is to clear all UI controls which are data binded.
        /// </summary>
        private void ClearScreen()
        {
        }

        /// <summary>
        /// This method is to bind all the UI control like dropdown list or list box etc with the required initial data, 
        /// </summary>
        private void FillLoadLookUpData()
        {
        }

        /// <summary>
        /// This method is to load the UI with initial set of data based of the business logic.
        /// </summary>
        private void InitializeScreen()
        {
            ClearScreen();
            FillLoadLookUpData();
        }

        /// <summary>
        /// This method is to copy the entity properties that need to be displayed in the UI controls to the UI control.
        /// Example - [pUser] is an instance of an entity and is filled with specific USER data.
        /// and this user instance is to be displayed is an UI control text boxes.
        /// A sample code will look like the following:
        ///  this.txtFirstName.Text = pUser.UserFirstName; 
        ///  this.txtLastName.Text  = pUser.UserLastName; 
        ///  this.txtLoginId.Text   = pUser.UserLoginID;
        /// </summary>
        private void TranslateEntityToUIControls(Sys_ErrorLog pSys_ErrorLog)
        {
            this.lblErrorLogPrimaryID.Text = Convert.ToString(pSys_ErrorLog.ErrorLogPrimaryID);
            this.lblApplicationName.Text = pSys_ErrorLog.ApplicationName;
            this.lblMethodName.Text = pSys_ErrorLog.MethodName;
            this.lblErrorMessage.Text = pSys_ErrorLog.ErrorMessage;
            this.lblStackTrace.Text = pSys_ErrorLog.StackTrace;
        }

        /// <summary>
        /// This method is to copy the user entered data from the UI controls to the entity instance that will be used to sent the entity to any other layer.
        /// Example - [pUser] is an instance of an entity and is to be filled with specific USER data that has been captured in the screen.
        /// A sample code will look like the following:
        ///  pUser.UserFirstName = this.txtFirstName.Text; 
        ///  pUser.UserLastName  = this.txtLastName.Text; 
        ///  pUser.UserLoginID   = this.txtLoginId.Text; 
        /// </summary>
        private void TranslateUIControlsToEntity(Sys_ErrorLog pSys_ErrorLog)
        {
            pSys_ErrorLog.ApplicationName = "Dasideen";
            pSys_ErrorLog.MethodName = "Update";
            pSys_ErrorLog.ErrorMessage = "For Inserting new Sys_ErrorLog entity data to database,[EntityState] attribute should be [New]";
            pSys_ErrorLog.StackTrace = "Dao";

            pSys_ErrorLog.Sys_CreatedByID = "-1";
        }

        private void LoadSys_ErrorLogList()
        {
            try
            {
                List<Sys_ErrorLog> lSys_ErrorLogList = new List<Sys_ErrorLog>();
                SiteAdminContentManagementBus lSiteAdminContentManagementBus = new SiteAdminContentManagementBus();
                lSys_ErrorLogList = lSiteAdminContentManagementBus.GetAllSys_ErrorLogDetails();

                this.gvdErrorLog.DataSource = lSys_ErrorLogList;
                this.gvdErrorLog.DataBind();
                
            }
            catch (Exception ex)
            {
                ExceptionUtility.ExceptionHandler(ex, Server.MapPath("~/"));
            }
        }

        protected void gvdErrorLog_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.gvdErrorLog.PageIndex = e.NewPageIndex;
            LoadSys_ErrorLogList();
        }
        #endregion Private Methods

    }
}